import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const tokenRef = ref(localStorage.getItem('token') || '')
  const token = computed(() => tokenRef.value)
  const certified = computed(() => tokenRef.value !== '')
  const showLoginDialog = ref(false)
  const setToken = (token: string) => {
    tokenRef.value = token
    localStorage.setItem('token', token)
  }

  const removeToken = () => {
    tokenRef.value = ''
    localStorage.removeItem('token')
  }

  const userInfo = computed(() => {
    const strings = token.value.split('.') //截取token，获取载体
    const jwt = JSON.parse(
      decodeURIComponent(
        escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))
      )
    )
    return JSON.parse(jwt['sub'])
  })

  return {
    token,
    certified,
    showLoginDialog,
    userInfo,
    setToken,
    removeToken,
  }
})
